package com.device.android

import android.graphics.Color
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.base.constant.What
import com.base.decoration.LinearDividerItemDecoration
import com.base.exp.dpToPx
import com.device.android.adapter.UsbAdapter
import com.device.android.databinding.ActivityMainBinding
import com.im.event.DefaultEvent
import com.im.event.observe.observeEvent

class MainActivity : AppCompatActivity() {
    private val usbAdapter by lazy { UsbAdapter() }
    private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        eventCallback()
        init()
        updateUsbList()
    }

    private fun init() {
        val height = dpToPx(10f)
        val decoration = LinearDividerItemDecoration(height, Color.WHITE)
        binding.recyclerView.apply {
            adapter = usbAdapter
            addItemDecoration(decoration)
        }
    }

    private fun eventCallback() {
        observeEvent<DefaultEvent> {
            when (it.what) {
                What.USB -> updateUsbList()
            }
        }
    }

    private fun updateUsbList() {
        val usbDevices: MutableList<UsbDevice?> = ArrayList()
        val usbManager = getSystemService(USB_SERVICE) as UsbManager?
        val deviceList = usbManager?.deviceList

        deviceList?.values?.let {
            usbDevices.addAll(it)
        }
        usbAdapter.notifyList(usbDevices)
    }
}